Overview:
print("Hello world")
Python is a interpreted, high level programming language created by Dutch programmer Guido van Rossum and released in 1991. Python is a programming language that lets you work more quickly and integrate your systems more effectively.:
1. Easy to learn with simpler syntax:</br> 2. Large number of open source libraries to assist us in every stage of data analyst</br> 3. Wider community support</br> 4. One for All</br> 5. Large availability of learning resources and materials</br>
1. Easy to learn with simpler syntax:
Python has one of the simplest syntax among all programming languages. It is more like simple English as opposed to the complex syntax of Java or C++ making it very beginner friendly and easy to learn,so anyone starting can learn it more easily and in a relatively short period of time.
2. Large number of open source libraries to assist us in every stage of data analyst
Python has a large number of open source libraries which contain a large number of predefined functions to perform many of the operations required in the data analyst which saves our time and efforts to write code each time for different operations (numpy, pandas, matplotlib, seaborn...)
3. Wider community support:
Python is one of the most widely used languages in various fields resulting into a very large,widespread and diverse community,so it is easier to get community support if you face any issues with a particular tool or encounter any problem while working upon your project. Python document is open and easy to understand the link here.
4. One for all
This is a key point which distinguishes Python from its competitors. While working on a data analyst project, it is not only all about data analyst. For example, in real world data is always not well organized and presented in forms of
excel sheetsandcsvfiles. Most of the time,data needs to be extracted from various different sources and its insights and results need to be presented in interactive ways across different platforms like a website,...So,it will require the integration of the processes of web scraping, data wrangling, cleaning... This integration is easier in Python because it has rich libraries resources for these tasks as well apart from Data Analyst making it easier for the developer,the feature which is lacking in most other languages.Built-in libraries and external libraries are powerful for many tasks, especially for data science, data engineer and data analysis:
- Scientific computing: numpy, numba, etc.
- AWS interaction: boto3
- Image processing: opencv, pillow, albumentation, etc.
- Machine learning and Deep learning framework: tensorflow, pytorch, onnx, sklearn, etc.
- Data processing and visualization: pandas, pyyaml, matplotlib, seaborn etc.
5. Large availability of learning resources and materials
Python has a large number of online learning materials and resources many of which are beginner friendly thus providing the programmer a large number of options to choose from in their learning journey.
In Stack Overflow survey 2021
% of developers who are not developing with the language or technology but have expressed interest in developing with it
- Indention, not braces
- Everything is an object
- Comments
- Variable
- Dynamic references, strong types
- Attributes and methods
- Duck typing
- Import
- Mutable and immutable objects
Python uses whitespace (tabs or spaces) to structure code instead of using braces as in many other languages like R, C++, Java, and Perl. A colon denotes the start of an indented code block after which all of the code must be indented by the same amount until the end of the block
Four spaces as your default indentation and replacing tabs with four spaces. (Jupyter notebook: Ctrl + ])
for i in [1,2,3]:
print(i)
print("Block 1")
print("--End block 1--")
1 Block 1 2 Block 1 3 Block 1 --End block 1--
Every number, string, data structure, function, class, module, and so on exists in the Python interpreter in its own “box,” which is referred to as a Python object. Each object has an associated type (e.g., string or function) and internal data.
type("Hello world")
str
type(1)
int
Any text preceded by the hash mark (pound sign) # is ignored by the Python interpreter.
# Câu lệnh này để in ra đoạn Hello world
# print("Hello world")
print("Hello world") # print("Hello world")
Hello world
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. </br>
The assignment statement gives a value to a variable.
The assignment token, =, should not be confused with equals, which uses the token ==
message = "What’s up, Doc?"
n = 17
pi = 3.14159
sum_nums = 5 + 3
print(sum_nums)
8
sum_nums = 10
print(sum_nums)
10
Variable names can be arbitrarily long. Some rules while naming Python variable:
- Python variable name can contain only alphabet a-z A-Z, digit 0-9 and underscore _, cannot contain special character ! @ # $ % ^ & * ( ) - = + { } : " ; , . / ?
- Python variable name cannot start with a digit, it can only start with alphabet or underscore. Example: 1abc is bad name, abc1 and _1abc are good names.
- Python variable name is case-sentitive. Example: abc, Abc, aBC are different variables.
- Can't used keyword
List of keywords
and |
as |
assert |
break |
class |
continue |
def |
del |
elif |
else |
except |
False |
finally |
for |
from |
global |
if |
import |
in |
is |
lambda |
None |
nonlocal |
not |
or |
pass |
raise |
return |
True |
while |
with |
yield |
tcb = 5000000
type(tcb)
int
tcb = "hello world"
type(tcb)
str
xez_123 = 1000
xez_123
1000
In contrast with many compiled languages, such as Java and C++, object references in Python have no type associated with them.
Objects in Python typically have both attributes (other Python objects stored “inside” the object) and methods (functions associated with an object that can have access to the object’s internal data). Both of them are accessed via the syntax
obj.method_name
c = "Hello World"
type(c)
str
c.upper()
'HELLO WORLD'
dir(c)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
help(c.upper)
Help on built-in function upper:
upper() method of builtins.str instance
Return a copy of the string converted to uppercase.
dir(object)
This function will return all the properties and methods, even built-in properties which are default for all object.
help(object.method)
Returns a help page.
Equivalent</br>
Shift + Tab
help(c.upper)
Help on built-in function upper:
upper() method of builtins.str instance
Return a copy of the string converted to uppercase.
c.upper
Duck typing
Often you may not care about the type of an object but rather only whether it has certain methods or behavior. This is sometimes called “duck typing,” after the saying “If it walks like a duck and quacks like a duck, then it’s a duck.”
Import
Three different ways to import names into the current namespace, and to use them:
# Single identifier random is added to the current namespace.
import random
random.randint(1,6)
2
random.randint(1,100)
77
from random import randint
randint(1,6)
5
# We can make things shorter by importing a module under a different name
import random as rd
rd.randint(1,6)
1
# NOT RECOMMEND
# from random import *
# randint(1,6)
Standard Python scalar types
| Type | Description | Example |
|---|---|---|
int |
Arbitrary precision signed integer | 3, 5, 100 |
float |
Double-precision (64-bit) floating-point number (note there is no separate double type) | 3.0, 1.2, 108.3 |
str |
String type; holds Unicode (UTF-8 encoded) strings | "Hello world", "3.0", "5" |
None |
The Python “null” value (only one instance of the None object exists) | None |
bool |
A True or False value | True, False |
bytes |
Raw ASCII bytes (or Unicode encoded as bytes) | b'espa\xc3\xb1ol' |
The primary Python types for numbers are int and float.
ival = 871
fval = 871.0
type(ival)
int
type(fval)
float
# Integer division not resulting in a whole number will always yield a floating-point number:
3/2
1.5
1 + 3
4
4/2
2.0
1 + 2
3
5 *6
30
' or double quotes "''' or """a = 'one way of writing a string'
b = "another way"
c = """
This is a longer string that
spans multiple lines
"""
' tôi nói:"xin chào" '
' tôi nói:"xin chào" '
a = 'I said: "Hello"'
Indexing
a[2]
's'
a[-5]
'e'
Slicing
a[8:15]
'"Hello"'
a[2:6]
'said'
a[8:]
'"Hello"'
a[-3]
'i'
a[-6:]
'string'
a[5]
'a'
a
'one way of writing a string'
a = "Hello world"
a.upper()
a = a.upper()
a
We can access every character in a string by its index (index means the position, from 0 to the length - 1) string[index]
a
a[4]
a[-16:-9]
We can use negative index to access character from the end of a string
a[-27]
len(a)-1
-1
a[27]
The syntax string[:3] is called slicing and is implemented for many kinds of Python sequences.
a = 'one way of writing a string'
a[4:7]
Adding two strings together concatenates (+) them and produces a new string
a + " "+ b
| Method | Description | Example |
|---|---|---|
.capitalize() |
Converts the first character to upper case | a = ' happy birthDay ' </br> >>> a.capitalize()</br> 'Happy birthDay ' |
.upper() |
Converts a string into upper case | >>> a.upper()</br> ' HAPPY BIRTHDAY ' |
.lower() |
Converts a string into lower case | >>> a.lower()</br> ' happy birthday ' |
.strip() |
Returns a trimmed version of the string | >>> a.strip()</br> 'happy birthDay' |
.rstrip() |
Returns a right trim version of the string | >>> a.rstrip()</br> ' happy birthDay' |
.lstrip() |
Returns a left trim version of the string | >>> a.lstrip()</br> 'happy birthDay ' |
.split() |
Splits the string at the specified separator, and returns a list | >>> a.split()</br> ['happy', 'birthDay'] |
.title() |
Splits the string at the specified separator, and returns a list | >>> a.title()</br> ' Happy Birthday ' |
More detail method for string the link here
string = " one way of writing a string "
string.split()
['one', 'way', 'of', 'writing', 'a', 'string']
string.title()
'One Way Of Writing A String'
string.strip()
'one way of writing a string'
string.upper()
' ONE WAY OF WRITING A STRING '
dir(string)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
help(a.split)
Help on built-in function split:
split(sep=None, maxsplit=-1) method of builtins.str instance
Return a list of the words in the string, using sep as the delimiter string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
a = 'one way of writing a string'
a.split()
a.split('f')
Note
string.split(separator, maxsplit)
separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"
# Splits the string at the specified separator, and returns a list
a.title()
d = " hello world "
d.strip()
a.index("w")
a + b
'one way of writing a stringanother way'
print(a+ " " +b)
one way of writing a string another way
We can combine other data type variable to print out with string format.
Use simple .format() method:
level = 1
a = 'MCI Python level '
a + level
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [29], in <cell line: 5>() 1 level = 1 3 a = 'MCI Python level ' ----> 5 a + level TypeError: can only concatenate str (not "int") to str
level = 1
a = 'MCI Python level {}'.format(level)
print(a)
MCI Python level 1
level = 1
course = 'Python'
a = 'MCI {} level {}'.format(course, level)
print(a)
MCI Python level 1
Use format() method with the index:
num_1 = 15
num_2 = 4
a = 'Sum of {} and {} is equal to {}'.format(num_1, num_2, num_1 + num_2)
print(a)
a = 'Sum of {0} and {1} is equal to {2}'.format(num_1, num_2, num_1 + num_2)
print(a)
a = 'Sum of {1} and {2} is equal to {0}'.format(num_1 + num_2, num_1, num_2)
print(a)
Write code that combines the following variables so print the output (Use `.format`)
“Python is powerful... and fast; plays well with others; Python is powerful... and fast; plays well with others; runs everywhere; is friendly & easy to learn; is Open.”
a = 'Python is powerful... and fast'
b = 'plays well with others'
c = 'runs everywhere'
d = 'is friendly & easy to learn'
e = 'is Open.'
a = 'Python is powerful... and fast'
b = 'plays well with others'
c = 'runs everywhere'
d = 'is friendly & easy to learn'
e = 'is Open'
print("{0}; {1}; {2}; {3}; {4}.".format(a,b,c,d,e))
a = "xin chào"
val = "español"
val_utf8 = val.encode('utf-8')
val_utf8.decode('utf-8')
The two boolean values in Python are written as True and False.
True and True
None is the Python null value type. If a function does not explicitly return a value, it implicitly returns None
a = None
a is None
A date in Python is not a data type of its own, the built-in Python datetime module provides datetime, date, and time types. The datetime type combines the information stored in date and time The datetime module
import datetime as dt
dt = dt.datetime(2011, 10, 29, 20, 30, 21)
dt
datetime.datetime(2011, 10, 29, 20, 30, 21)
type(dt)
datetime.datetime
dt.day
29
dt.minute
30
- Arithmetic operators
- Comparisons
- Combining conditions with logical operators
Operators are special tokens that represent computations like addition, multiplication and division.</br>
The values the operator works on are called operands.
Python supports the following arithmetic operators:
| Operator | Purpose | Example | Result |
|---|---|---|---|
+ |
Addition | 2 + 3 |
5 |
- |
Subtraction | 3 - 2 |
1 |
* |
Multiplication | 8 * 12 |
96 |
/ |
Division | 100 / 7 |
14.28.. |
// |
Floor Division | 100 // 7 |
14 |
% |
Modulus/Remainder | 100 % 7 |
2 |
** |
Exponent | 5 ** 3 |
125 |
5/3
1.6666666666666667
5//3
1
5%3
2
2 * 3 ** 4 / 6
8%5
20 + 4 * 10
60
(20 + 4) * 10
240
(2 *(3 ** 4)) / 6
27.0
3 ** 4
81
2*81
162
162/6
Python also provides several operations for comparing numbers & variables.
| Operator | Description |
|---|---|
== |
Check if operands are equal |
!= |
Check if operands are not equal |
> |
Check if left operand is greater than right operand |
< |
Check if left operand is less than right operand |
>= |
Check if left operand is greater than or equal to right operand |
<= |
Check if left operand is less than or equal to right operand |
The result of a comparison operation is either True or False (note the uppercase T and F). These are special keywords in Python.
a = 5
b = 4
a > b
True
a >= b
True
a < b
False
The logical operators and, or and not operate upon conditions and True & False values (also known as booleans). and and or operate on two conditions, whereas not operates on a single condition.
The and operator returns True when both the conditions evaluate to True. Otherwise, it returns False.
a |
b |
a and b |
|---|---|---|
True |
True |
True |
True |
False |
False |
False |
True |
False |
False |
False |
False |
x = 3
x > 0 and x < 5
True
x = 6
x > 0 and x < 5
False
The or operator returns True if at least one of the conditions evaluates to True. It returns False only if both conditions are False.
a |
b |
a or b |
|---|---|---|
True |
True |
True |
True |
False |
True |
False |
True |
True |
False |
False |
False |
x = 4
x > 0 or x < 5
x = 6
x > 0 or x < 5
The not operator returns False if a condition is True and True if the condition is False.
x = 3
not x <5
False
Logical operators can be combined to form complex conditions. Use round brackets or parentheses ( and ) to indicate the order in which logical operators should be applied.
number = 3
number == 5 or number == 6
False
number == 5 or 6
6
A list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements. There are several ways to create a new list. The simplest is to enclose the elements in square brackets [ and ]
a_list = [10, 20, 30, 40]
b_list = ["spam", "bungee", "swallow","hello","world"]
Indexing
a_list[1]
20
Slicing
b_list[1:3]
['bungee', 'swallow']
b_list[2:]
['swallow', 'hello', 'world']
dir(b_list)
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
| Method | Description | |
|---|---|---|
.append() |
Adds an element at the end of the list | |
.pop() |
Removes the element at the specified position | |
.remove() |
Removes the first item with the specified value | |
.index() |
Returns the index of the first element with the specified value | |
.extend() |
Add the elements of a list (or any iterable), to the end of the current list | |
.insert() |
Adds an element at the specified position | |
.count() |
Returns the number of elements with the specified value | |
.reverse() |
Reverses the order of the list | |
.sort() |
Sorts the list | Example |
.clear() |
Removes all the elements from the list |
a_list = [10, 20, 30, 40]
a_list.append(80)
a_list
[10, 20, 30, 40, 80]
a_list.pop()
80
a_list
[10, 20, 30, 40]
a_list.insert(1,80)
a_list
[10, 80, 20, 30, 40]
a_list.index(30)
3
a_list.extend(b_list)
a_list
[10, 80, 20, 30, 40, 'spam', 'bungee', 'swallow', 'hello', 'world']
a_list.count(80)
1
a_list
a_list[-4:]
a_list
# Assign value to element in list
a_list[5] = 0
a_list
a_list = [50,10,30]
a_list[1] = 5
a_list
[50, 5, 30]
string_a = "hello"
string_a[1] = "w"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [26], in <cell line: 1>() ----> 1 string_a[1] = "w" TypeError: 'str' object does not support item assignment
a_list
[50, 5, 30]
a_list.sort()
a_list = [50,10,30]
sorted(a_list, reverse= True)
[50, 30, 10]
help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
a_list
[50, 10, 30]
help(a_list.reverse)
Help on built-in function reverse:
reverse() method of builtins.list instance
Reverse *IN PLACE*.
mystring = "python is the best language for data analyst"
lst_str = mystring.split()
new_lst = lst_str[:5]
new_lst
['python', 'is', 'the', 'best', 'language']
new_lst.sort()
print(new_lst)
['best', 'is', 'language', 'python', 'the']
A tuple, like a list, is a sequence of items of any type. The printed representation of a tuple is a comma-separated sequence of values, enclosed in parentheses. Tuple is a fixed-length, immutable sequence of Python objects.
tup = ("hello", "hello", 67, "Dup", 20, "Actress", "Geo")
| Method | Description |
|---|---|
.count() |
Returns the number of times a specified value occurs in a tuple |
.index() |
Searches the tuple for a specified value and returns the position of where it was found |
tup.count("hello")
tup.index(20)
tup[1] = 30
It is a flexibly sized collection of key-value pairs, where key and value are Python objects. One approach for creating one is to use curly braces {} and colons to separate keys and values
d1 = {'a' : 'some value', 'b' : [1, 2, 3, 4]}
d1["a"]
'some value'
d1["b"]
[1, 2, 3, 4]
| Method | Description |
|---|---|
.keys() |
Returns a list containing the dictionary's keys |
.items() |
Returns a list containing a tuple for each key value pair |
.values() |
Returns a list of all the values in the dictionary |
.get() |
Returns the value of the specified key |
.update() |
Updates the dictionary with the specified key-value pairs |
.setdefault() |
Returns the value of the specified key. If the key does not exist: </br>insert the key, with the specified value |
.pop() |
Removes the element with the specified key |
.popitem() |
Removes the last inserted key-value pair |
d1.keys()
dict_keys(['a', 'b'])
d1.items()
dict_items([('a', 'some value'), ('b', [1, 2, 3, 4])])
d1.values()
dict_values(['some value', [1, 2, 3, 4]])
d1["c"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Input In [41], in <cell line: 1>() ----> 1 d1["c"] KeyError: 'c'
d1.get("c",0)
0
d1
{'a': 'some value', 'b': [1, 2, 3, 4]}
d1.get("b",5)
[1, 2, 3, 4]
d1.setdefault("b",0)
d1.setdefault("c",0)
0
d1
{'a': 'some value', 'b': [1, 2, 3, 4], 'c': 0}
e = {"e":80}
d1.update(e)
d1
{'a': 'some value', 'b': [1, 2, 3, 4], 'c': 0, 'e': 80}
A set is an unordered collection of unique elements.
set([2, 2, 2, 1, 3, 3])
{1, 2, 3}
{2,3,3,3,3,2,3,8,8}
{2, 3, 8}
| Method | Alternative syntax | Description |
|---|---|---|
a.add(x) |
N/A | Add element x to the set a |
a.clear() |
N/A | Reset the set a to an empty state, discarding all of its elements |
a.remove(x) |
N/A | Remove element x from the set a |
a.pop() |
N/A | Remove an arbitrary element from the set a, raising KeyError if the set is empty |
a.union(b) |
a | b |
All of the unique elements in a and b |
a.update(b) |
a |= b |
Set the contents of a to be the union of the elements in a and b |
a.intersection(b) |
a & b |
All of the elements in both a and b |
a.intersection_update(b) |
a &= b |
Set the contents of a to be the intersection of the elements in a and b |
a.difference(b) |
a - b |
The elements in a that are not in b |
a.difference_update(b) |
a -= b |
Set a to the elements in a that are not in b |
a.symmetric_difference(b) |
a ^ b |
All of the elements in either a or b but not both |
a.symmetric_difference_update(b) |
a ^= b |
Set a to contain the elements in either a or b but not both |
a.issubset(b) |
N/A | True if the elements of a are all contained in b |
a.issuperset(b) |
N/A | True if the elements of b are all contained in a |
a.isdisjoint(b) |
N/A | True if a and b have no elements in common |
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
a.union(b)
a | b
a.intersection(b)
a & b
# Sets are equal if and only if their contents are equal:
{1, 2, 3} == {3, 2, 1}
| Data type | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Example | ['apple', 'banana', 'orange'] | ('Book 1', 12.99, 35, 100) | {10, 20, 12, 12.5, 'Book'} | {'name': 'Joe', 'age': 10} |
| Mutable? | Mutable | Immutable | Mutable | Mutable |
| Iterable? | Yes ~ O(n) | Yes ~ O(n) | Yes ~ O(n) | Yes ~ O(n) | Use case | Data that needs to change | Immutable data | Unique items | Key/Value pairs |
# Init an integer
r = 1
print(r, type(r))
# Cast integer to float
t = float(r)
print(t, type(t))
# Cast float to integer
q = int(t)
print(q, type(q))
a = 30
float(a)
30.0
a = "ab"
type(a)
str
int(a)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [67], in <cell line: 1>() ----> 1 int(a) ValueError: invalid literal for int() with base 10: 'ab'
s = "3.14159"
fval = float(s)
ival = int(fval)
# float, int -> string ok
int("3")
int("hello")
lst = [1, 2.5, 'stringggg']
tup = tuple(lst)
lst1 = list(tup)
print(type(lst),type(tup),type(lst1))
# Init a list
w = [1, 2.5, 'stringggg',]
print(w, type(w))
# Cast list to set
z = set(w)
print(z, type(z))
# Cast set to list
x = list(z)
print(x, type(x))
# Init a tuple
w = (1, 2.5, 'stringggg')
print(w, type(w))
# Cast tuple to set
z = set(w)
print(z, type(z))
# Cast set to tuple
x = tuple(z)
print(x, type(x))
Python has several built-in keywords for conditional logic, loops, and other standard control flow concepts found in other programming languages.
We almost always need the ability to check conditions and change the behavior of the program accordingly
if condition:
STATEMENTS_1
else:
STATEMENTS_2
x = 20
y = 10
if x < y:
print("x <y")
else:
print("x > y")
print("Hello world")
x > y Hello world
if condition:
STATEMENTS
if x < y:
print("x <y")
print("Hello world")
Hello world
if condition1:
STATEMENTS_A
elif condition2:
STATEMENTS_B
else:
STATEMENTS_C
x = 10
y = 10
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x and y must be equal")
grade = 85
if grade> 95:
print("top")
elif grade >80:
print ("better")
elif grade > 60:
print ("good")
else:
print ("fail")
print("end block")
Chained conditional
One conditional can also be nested within another.
if condition1:
STATEMENTS_A
else:
if condtion2:
STATEMENTS_B
else:
STATEMENTS_C
if condition1:
STATEMENTS_A
elif condtion2:
if condtion3:
STATEMENTS_B
else:
STATEMENTS_C
else:
if condtion4:
STATEMENTS_D
else:
STATEMENTS_E
if condition1:
STATEMENTS_A
elif condtion2:
STATEMENTS_B
else:
STATEMENTS_C
x = 11
if 0 < x: # Assume x is an int here
if x < 10:
print("x is a positive single digit.")
Instead of the above which uses two if statements each with a simple condition, we could make a more complex condition using the and operator. Now we only need a single if statement:
if 0 < x and x < 10:
print("x is a positive single digit.")
Nested conditionals
forloops¶for loops are for iterating over a collection (like a list or tuple) or an iterater.</br>
The standard syntax for a for loop is:
for value in collection:
# do something with value
num_loop = 1
for i in [1,2,3]:
print("*"*6)
print("value i = {}".format(i))
print("Loop number {}".format(num_loop))
print("_"*6)
num_loop = num_loop + 1
print("--End loop FOR --")
****** value i = 1 End loop number 1 ______ ****** value i = 2 End loop number 2 ______ ****** value i = 3 End loop number 3 ______ --End loop FOR --
num_lst = [80, 30, 100, 90]
max_value = 0
for num in num_lst:
if num > max_value:
max_value = num
100
max_value
num_lst = [80, 30, 90,100]
max_value = num_lst[0]
for num in num_lst:
print("*"*6)
print("value of max_value: {}; value of num: {}".format(max_value, num))
if num > max_value:
print("The value of max_value: {}".format(max_value))
max_value = num
print("Then the value of max_value changes to: {}".format(max_value))
print("_"*6)
****** value of max_value: 80; value of num: 80 ______ ****** value of max_value: 80; value of num: 30 ______ ****** value of max_value: 80; value of num: 90 The value of max_value: 80 Then the value of max_value changes to: 90 ______ ****** value of max_value: 90; value of num: 100 The value of max_value: 90 Then the value of max_value changes to: 100 ______
max_value
100
num_lst = [80, 30, 100, 90]
max_value = num_lst[0]
for num in num_lst:
print("max_value là {}; num là {}".format(max_value, num))
print("--------")
if num > max_value:
max_value = num
print("max_value là {}".format(max_value))
lst = [3, 8, 200, 350, -30]
lst = [3, 8, 200, 350, -30]
min_value = lst[0]
for num in lst:
if num < min_value:
min_value = num
min_value
QUIZ:
Optional: Find max value in dictionary
dic_num = {"d": 90 , "t": 30, "n": 50, "r": 10}
*Hint: use .keys , for, list
Click to see solution!
dic_num = {"d": 90 , "t": 30, "n": 50, "r": 10}
keys_lst = list(dic_num.keys())
max_key = keys_lst[0]
for key in keys_lst:
if dic_num[key]>dic_num[max_key]:
max_key = key
max_value = dic_num[max_key]
max_value
</pre>
</details>
</div>
One common programming “pattern” is to traverse a sequence, accumulating a value as we go, such as the sum-so-far or the maximum-so-far.
The anatomy of the accumulation pattern includes:
nums = [1, 2, 3, 4] # 5, 6, 7, 8, 9, 10
accum = 0
for w in nums:
accum += w # equivalent accum = accum + w
accum
10
A for loop can be exited altogether with the break keyword
sequence = [1, 2, 0, 4, 6, 5, 2, 1]
total_until_5 = 0
for value in sequence:
if value == 5:
break
total_until_5 += value
total_until_5
13
my_str = "Mango banAna apple pear bananA grapes strawberry blueberry apPle blueberry KiWi apple blueberry manGo strawberry"
my_str = "Mango banAna apple pear bananA grapes strawberry blueberry apPle blueberry KiWi apple blueberry manGo strawberry"
d = {}
lst_words = my_str.split()
for word in lst_words:
w_lower = word.lower()
if w_lower in d:
d[w_lower] = d[w_lower] + 1
else:
d[w_lower] = 1
d
Method 2
my_str = "Mango banAna apple pear bananA grapes strawberry blueberry apPle blueberry KiWi apple blueberry manGo strawberry"
d = {}
lst_words = my_str.split()
for word in lst_words:
w_lower = word.lower()
d[w_lower] = d.get(w_lower,0) + 1
d
Nested iteration simply means that we will place one iteration construct inside of another. We will call these two iterations the outer iteration and the inner iteration.
for i in range(5):
for j in range(3):
print(i, j)
0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 3 0 3 1 3 2 4 0 4 1 4 2
range(5)
range(0, 5)
A while loop specifies a condition and a block of code that is to be executed until the condition evaluates to False or the loop is explicitly ended with break:
while condition:
# do something
x = 10
total = 0
while total <x :
total += 0.3235
total
10.028499999999998
x = 256
total = 0
while (x > 0) and (total < 500):
# if total > 500:
# break
total += x
x = x -100
total
468
x = 256
total = 0
while x > 0:
total += x
x = x + 100
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) Input In [88], in <cell line: 3>() 3 while x > 0: 4 total += x ----> 5 x = x + 100 KeyboardInterrupt:
x = 5
while x < 26:
x += 5 # x = x + 5
print (x)
Use a for loop if you know, before you start looping, the maximum number of times that you’ll need to execute the body. For example, if you’re traversing a list of elements, you know that the maximum number of loop iterations you can possibly need is “all the elements in the list”. Or if you need to print the 12 times table, we know right away how many times the loopwill need to run.
So any problem like “iterate this weather model for 1000 cycles”, or “search this list of words”, “find all prime numbers up to 10000” suggest that a for loop is best.
By contrast, if you are required to repeat some computation until some condition is met, and you cannot calculate in advance when (of if) this will happen, you’ll need a while loop.
We call the first case definite iteration — we know ahead of time some definite bounds for what is needed. The latter case is called indefinite iteration — we’re not sure how many iterations we’ll need — we cannot even establish an upper bound!
pass
pass is the “no-op” statement in Python. It can be used in blocks where no action is to
be taken
x = 0
if x < 0:
print('negative!')
elif x == 0:
# TODO: put something smart here
pass
else:
print('positive!')
range
The range function returns an iterator that yields a sequence of evenly spaced integers
num_loop = 1
for i in [1,2,3]:
print("*"*6)
print("value i = {}".format(i))
print("Loop number {}".format(num_loop))
print("_"*6)
num_loop = num_loop + 1
****** value i = 1 Loop number 1 ______ ****** value i = 2 Loop number 2 ______ ****** value i = 3 Loop number 3 ______
num_loop = 1
for i in range(1,4):
print("The value of i = {}".format(i))
print("Number loop: {}".format(num_loop))
num_loop += 1
The value of i = 1 Number loop: 1 The value of i = 2 Number loop: 2 The value of i = 3 Number loop: 3
list(range(1,4))
[1, 2, 3]
range(0, 10)
zip
“pairs” up the elements of a number of lists, tuples, or other sequences to create a list of tuples
seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three']
zipped = zip(seq1, seq2)
zipped
<zip at 0x2271136b300>
for i in zipped:
print(i)
print(type(i))
('foo', 'one')
<class 'tuple'>
('bar', 'two')
<class 'tuple'>
('baz', 'three')
<class 'tuple'>
enumerate
Enumerate, which returns a sequence of (i, value) tuples
for index, value in enumerate(collection):
# do something with value
a_list = [1,2,3]
for index, value in enumerate(a_list):
print(index,"--",value)
0 -- 1 1 -- 2 2 -- 3
sorted
Function returns a new sorted list from the elements of any sequence
sorted(iterable, key=None, reverse=False)
lst = [80,60,30,5]
sorted(lst)
[5, 30, 60, 80]
lst
[80, 60, 30, 5]
lst.sort()
lst
[5, 30, 60, 80]
List comprehensions are one of the most-loved Python language features. They allow you to concisely form a new list by filtering the elements of a collection, transforming the elements passing the filter in one concise expression.
With if
[expr for val in collection if condition]
Equivalent
result = []
for val in collection:
if condition:
# expr = val do something
result.append(expr1)
In general, with if&else
[expr1 if condition else expr2 for value incollection]
# Add 5 each number of lst_nums
lst_nums = [80,60,30,5]
result = []
for num in lst_nums:
value = num + 5
result.append(value)
result
[85, 65, 35, 10]
lst_nums = [80,60,30,5]
[num + 5 for num in lst_nums]
[85, 65, 35, 10]
# Add 5 each number of lst_nums if number <50 else = number
lst_nums = [80,60,30,5]
[num + 5 if num <50 else num for num in lst_nums]
[80, 60, 35, 10]
strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
result = []
for item in strings:
if len(item)>2:
result.append(item.upper())
result
strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
[x.upper() for x in strings if len(x) > 2]
Set and dict comprehensions
dict_comp = {key-expr : value-expr for value in collection if condition}
set_comp = {expr for value in collection if condition}
lst = ["a","b","c","d"]
dic_num = {val: i for i,val in enumerate(lst)}
dic_num
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
lst = ["a","b","c","d","a","c"]
set_comp = {val for val in lst}
set_comp
{'a', 'b', 'c', 'd'}
Nested list comprehensions
all_data = [['John', 'Emily', 'Michael', 'Mary', 'Steven'],
['Maria', 'Juan', 'Javier', 'Natalia', 'Pilar']]
result = [name for names in all_data for name in names if name.count('e') >= 2]
result
['Steven']
<DRY>-DON’T REPEAT YOURSELF
def add_5 (lst_nums):
return [num + 5 for num in lst_nums]
lst_nums = [80,60,30,5]
add_5(lst_nums)
[85, 65, 35, 10]
lst_nums_b = [15,35,25,10]
add_5(lst_nums_b)
[20, 40, 30, 15]
A function is a named sequence of statements that belong together. Their primary purpose is to help us organize programs into chunks that match how we think about the problem.
Two kinds of functions in Python.
- Built-in functions that are provided as part of Python: print(), input(), type(), float(), int() ...
- Functions that we define ourselves and then use.
The syntax for a function definition is:
def NAME (PARAMETERS):
STATEMENTS
Defining a new function does not make the function run. To execute the function, we need a **function call. (function invocation**)The way to invoke a function is to refer to it by name, followed by parentheses.*
def greet ():
print("Xin chào bạn Quang")
print("Rất vui được gặp bạn")
print("Hello")
Hello
greet()
Xin chào bạn Quang Rất vui được gặp bạn
for i in range(5):
greet()
print("-----")
Xin chào bạn Quang Rất vui được gặp bạn ----- Xin chào bạn Quang Rất vui được gặp bạn ----- Xin chào bạn Quang Rất vui được gặp bạn ----- Xin chào bạn Quang Rất vui được gặp bạn ----- Xin chào bạn Quang Rất vui được gặp bạn -----
def add_value (lst_nums,value):
return [num + value for num in lst_nums]
lst_nums = [80,60,30,5]
add_value(lst_nums,10)
[90, 70, 40, 15]
With parameters, functions are even more powerful, because they can do pretty much the same thing on each invocation, but not exactly the same thing.
def greet (name):
print("Xin chào bạn " + name)
print("Rất vui được gặp bạn")
greet("Nam")
Xin chào bạn Nam Rất vui được gặp bạn

Not only can you pass a parameter value into a function, a function can also produce a value.
- The return statement is followed by an expression which is evaluated. Its result is returned to the caller as the “fruit” of calling this function
A return statement, once executed, immediately terminates execution of a function, even if it is not the last statement in the function.
def square(number):
return number*number
print("Hello world")
square (8)
64
def add_value (lst_nums,value=5):
return [num + value for num in lst_nums]
lst_nums = [80,60,30,5]
add_value(lst_nums,3)
[83, 63, 33, 8]
def square(number = 3):
return number*number
Each call of the function creates new local variables, and their lifetimes expire when the function returns to the caller.
def add_five(num):
add_num = 5
result = num + add_num
return result
a = add_five(5)
add_num = 8
print(a)
print(a,"&", add_num)
a = add_five(5)
print(a)
10 10 & 8 10
One of the most important ways that computer programmers take a large problem and break it down into a group of smaller problems.
def square(x):
y = x * x
return y
def sum_of_squares(x,y,z):
a = square(x)
b = square(y)
c = square(z)
return a + b + c
sum_of_squares(1,2,3)
14
When you are working with functions it is really important to know the order in which statements are executed.
def add_five(num):
add_num = 5
result = num + add_num
return result
print("hello")
for i in range(5):
print(i)
add_five(5)
0 1 2 3 4
10
Write a function named number_test that takes a number as input. If the number is greater than 8, the function should return “Greater than 8.” If the number is less than 8, the function should return “Less than 8.” If the number is equal to 8, the function should return “Equal to 8.”
def number_test(num):
if num> 8:
return "Greater than 10."
elif num == 8:
return "Equal to 8."
else:
return "Less than 8."
The syntax for lambda function:
lambda arguments: expression
def add_five(num):
add_num = 5
result = num + add_num
return result
add_five(5)
10
a = lambda x : x+5
a(8)
13
add_five(8)
13
Write a lambda function that takes a string as input and then returns the uppercase first character of the string
a = lambda string : string[0].upper()
New functions from existing ones by partial argument application.
def add_numbers(x, y):
return x + y
add_five = lambda y : add_numbers(5,y)
add_five(6)
def squares(n=10):
print('Generating squares from 1 to {0}'.format(n ** 2))
for i in range(1, n + 1):
yield i ** 2
gen = squares()
gen
<generator object squares at 0x0000027908F33200>
list(gen)
Generating squares from 1 to 100
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Another even more concise way to make a generator is by using a generator expression.
gen = (x ** 2 for x in range(100))
gen
There are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that you can use in a path. A single period (.) for a folder name is shorthand for “this directory.” Two periods (..) means “the parent folder.”
Figure shows an example of some folders and files. When the cwd is set to C:\bacon, the relative paths for the other folders and files are set as they are in the figure.
The .\ at the start of a relative path is optional. For example, .\spam.txt and spam.txt refer to the same file.
To open a file for reading or writing, use the built-in open function with either a relative or absolute file path. By default, the file is opened in read-only mode 'r'.
| Mode | Description |
|---|---|
r |
Read-only mode |
w |
Write-only mode; creates a new file (erasing the data for any file with the same name) |
x |
Write-only mode; creates a new file, but fails if the file path already exists |
a |
Append to existing file (create the file if it does not already exist) |
r+ |
Read and write |
b |
Add to mode for binary files (i.e., 'rb' or 'wb') |
t |
Text mode for files (automatically decoding bytes to Unicode). </br>This is the default if not specified. Add t to other modes to use this (i.e., 'rt' or 'xt') |
Note: When you use open to create file objects, it is important to explicitly close the file when you are finished with it.
path = 'data/travel_plans.txt'
fl = open(path)
fl.readlines()
'D:\GitHub\sword\pylv1_mcivn\data\travel_plans.txt'
path = r'data/travel_plans.txt'
fl = open(path)
for line in fl:
print(line)
fl.close()
This summer I will be travelling. I will go to... Italy: Rome Greece: Athens England: London, Manchester France: Paris, Nice, Lyon Spain: Madrid, Barcelona, Granada Austria: Vienna I will probably not even want to come back! However, I wonder how I will get by with all the different languages. I only know English!
| Method | Use | Explanation |
|---|---|---|
write |
fl.write(astring) |
Add a string to the end of the file. fl must refer to a </br>file that has been opened for writing. |
read(n) |
fl.read() |
Read and return a string of n characters, or the entire file </br> as a single string if n is not provided. |
readline(n) |
fl.readline() |
Read and return the next line of the file with all text up to and </br> including the newline character. If nis provided as a parameter,</br> then only n characters will be returned if the line is longer than n. |
readlines(n) |
fl.readlines() |
Returns a list of strings, each representing a single line of the file.</br> If n is not provided then all lines of the file are returned. </br> If n is provided then n characters are read but n is rounded up so that an entire line is returned. |
path = r'data/travel_plans.txt'
fl = open(path)
fl.read()
'This summer I will be travelling.\nI will go to...\nItaly: Rome\nGreece: Athens\nEngland: London, Manchester\nFrance: Paris, Nice, Lyon\nSpain: Madrid, Barcelona, Granada\nAustria: Vienna\nI will probably not even want to come back!\nHowever, I wonder how I will get by with all the different languages.\nI only know English!'
path = r'data/travel_plans.txt'
fl = open(path)
fl.readline()
'This summer I will be travelling.\n'
path = r'data/travel_plans.txt'
fl = open(path)
fl.readlines()
['This summer I will be travelling.\n', 'I will go to...\n', 'Italy: Rome\n', 'Greece: Athens\n', 'England: London, Manchester\n', 'France: Paris, Nice, Lyon\n', 'Spain: Madrid, Barcelona, Granada\n', 'Austria: Vienna\n', 'I will probably not even want to come back!\n', 'However, I wonder how I will get by with all the different languages.\n', 'I only know English!']
fl.write("Hello world")
--------------------------------------------------------------------------- UnsupportedOperation Traceback (most recent call last) Input In [75], in <cell line: 1>() ----> 1 fl.write("Hello world") UnsupportedOperation: not writable
The Python with statement makes using context managers easy. The general form of a with statement is:
with <create some object that understands context> as <some name>:
do some stuff with the object
...
path = r'data/travel_plans.txt'
with open(path) as fl:
for line in fl.readlines():
print(line)
This summer I will be travelling. I will go to... Italy: Rome Greece: Athens England: London, Manchester France: Paris, Nice, Lyon Spain: Madrid, Barcelona, Granada Austria: Vienna I will probably not even want to come back! However, I wonder how I will get by with all the different languages. I only know English!
Here’s a foolproof recipe for processing the contents of a text file.
fname = "yourfile.txt"
with open(fname, 'r') as fileref: # step 1
lines = fileref.readlines() # step 2
for lin in lines: # step 3
#some code that references the variable line
#some other code not relying on fileref # step 4
Optional: Extract list of cities and list of countries in file
path = 'data/travel_plans.txt'
*Hint: use str.split , str.strip , for, with open(path) as fl,fl.readlines, list.append, list.extend
lst_country = ['Italy', 'Greece', 'England', 'France', 'Spain', 'Austria']
lst_city = ['Rome', 'Athens', 'London', ' Manchester', 'Paris', ' Nice', ' Lyon', 'Madrid', ' Barcelona', ' Granada', 'Vienna']
Click to see solution!
path = 'data/travel_plans.txt'
with open(path) as fl:
lst_country = []
lst_city = []
for line in fl.readlines():
if ":" in line:
a = line.split(":")
lst_country.append(a[0])
lst_city.extend(a[1].strip().split(","))
</div>
The default behavior for Python files (whether readable or writable) is text mode, which means that you intend to work with Python strings (i.e., Unicode). If you find yourself regularly doing data analysis on non-ASCII text data, mastering Python’s Unicode functionality will prove valuable. See Python’s online documentation for much more.
Programming is a complex process. Since it is done by human beings, errors may often occur. Programming errors are called bugs and the process of tracking them down and correcting them is called debugging. Types bug:
Syntax error
print"Hello world"
Input In [82] print"Hello world" ^ SyntaxError: invalid syntax
Runtime error
int("a")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [84], in <cell line: 1>() ----> 1 int("a") ValueError: invalid literal for int() with base 10: 'a'
Semantic error (logic error)
a = lambda x : x + 8
a (5)
13
How to Avoid Debugging
An exception is a signal that a condition has occurred that can’t be easily handled using the normal flow-of-control of a Python program. Exceptions are often defined as being “errors” but this is not always the case.
The try/except control structure provides a way to process a run-time error and continue on with program execution With try/except, you tell the python interpreter:
Try to execute a block of code, the “try” clause.
- If the whole block of code executes without any run-time errors, just carry on with the rest of the program after the try/except statement.
If a run-time error does occur during execution of the block of code:
- skip the rest of that block of code (but don’t exit the whole program)
- execute a block of code in the “except” clause
- then carry on with the rest of the program after the try/except statement
The syntax for try & except function:
try:
<Some Code.... >
except <ErrorType>:
<exception handler code block>
finally:
<Some code .....(always executed)>
items = ['a', 'b']
third = items[2]
print("hello world")
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Input In [87], in <cell line: 2>() 1 items = ['a', 'b'] ----> 2 third = items[2] 3 print("hello world") IndexError: list index out of range
items = ['a', 'b']
try:
third = items[2]
except IndexError:
print("I can't do it")
print("hello world")
I can't do it hello world
for i in ["1",'2',"a"]:
try:
print(int(i))
except:
print("Toi khong the lam duoc")
1 2 Toi khong the lam duoc
The input() function allows user input.
input(prompt) -> return string
a = input("Nhap diem cua ban")
Nhap diem cua ban5
print(a)
5
int(a)
from optional_1 import score
score()
Nhập điểm của bạn (Điểm phải là số và trong khoảng từ 0 đến 100): -10 Điểm của bạn phải nằm trong khoảng từ 0 đến 100 Nhập điểm của bạn (Điểm phải là số và trong khoảng từ 0 đến 100): 150 Điểm của bạn phải nằm trong khoảng từ 0 đến 100 Nhập điểm của bạn (Điểm phải là số và trong khoảng từ 0 đến 100): a Điểm của bạn phải là số! Nhập điểm của bạn (Điểm phải là số và trong khoảng từ 0 đến 100): 95 Bạn đã đỗ
Hint: use some function
while, try except, break, if, True, input
Bạn đầu tư 100 triệu tiền cổ phiếu Vietcombank với mức giá 40.000đ/1 cổ phiếu (1/1/2019), trong đó số tiền vay là 30 triệu. Sau 2 năm (1/1/2021) giá trị 1 cổ phiếu VCB là 80.000đ/1 cổ phiếu, tương đương giá trị là 200 triệu.
Giả định bạn đã bán hết số lượng cổ phiếu ngày 1/1/2021 với mức phí 0.5%, và lãi vay mua chứng khoán là 10%/năm. Thì số tiền thu về là bao nhiêu?
Lãi vay chứng khoán không đổi trong 2 năm nắm giữ chứng khoán mức phí giao dịch chứng khoán tính trên tổng giá trị bán đi
stocks = ['VCB', 'HPG', 'FPT', 'TCB']
prices = [80, 40, 100, 50]
Câu hỏi: Tìm cổ phiếu có mức giá cao nhất?
Trình bày 1 case study bạn đang gặp phải và có thể dùng python để xử lý được
Sinh viên nhận được điểm Pass/Fail. Nếu điểm >= 65 (trên thang 100) đạt "Pass". Đối với mức điểm thấp hơn sẽ được coi là "Fail". Bên cạnh đó, mức điểm > 95 là "Top Score".
Viết function sao cho:
print(exam_grade(65)) # Should be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(100)) # Should be Top Score
Viết function sao cho:
print(greeting()) # Should be welcome
print(greeting('Peter')) # Should be Welcome back Peter!
print(greeting('Tên bất kì')) # Should be "Hello there, " + name
Write a function which has input as an integer and return the sum from 1 to that integer.
Example: my_sum_function_1(8) = 36
Write a function which has input as an integer and return the sum from 1 to that integer but only even numbers.
Example: my_sum_function_2(10) = 30
Write a function to check input number is a prime number or a composite number. If it is a composite number, print all of its divisor.
Example: check_prime_composite(10) -> 2,5 composite
Note:</br> A prime number is a whole number greater than 1 whose only factors are 1 and itself.
Write a function to calculate the factorial of an integer.
Note:
Example: 5! = 5\4*3*2*1*
Generate randomly 3 numbers a, b, cto form a quadratic equation. Write a function to solve this equation.
Hint: Solution quadratic equation
Check if delta < 0 -> No solution
Check if delta == 0 $$ x = \frac{-b}{2a} $$
Check if delta > 0 -> Calculation x1, x2 $$ x_1 = \frac{-b - \sqrt{delta}}{2a} $$